//
//  DeviceHomeViewController.swift
//  XSQWiFi
//
//  Created by XinPengLee on 2025/5/7.
//  设备

import UIKit
import NetworkExtension
 

class DeviceHomeViewController: UIViewController {

    @IBOutlet weak var gradiesView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    var collectionLayout: UICollectionViewFlowLayout!

    // 网络状态 0 没网络 1 WiFi  2 4G网络
    // 局域网是否有接收端
    var recsocket:GCDAsyncUdpSocket!
    var sendSocket:GCDAsyncUdpSocket!
    // SSDP 常量
       private let SSDP_MULTICAST_IP = "239.255.255.250"
       private let SSDP_PORT: UInt16 = 1900
       private let SSDP_SEARCH_TIMEOUT: TimeInterval = 5.0
    private var searchTimer: Timer?
     private var isScanning = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigation.bar.isHidden = true
        gradiesView.setupGradientBackground(startColor: UIColor().colorConversionHex(Color_Value: "#90BAF7"), endColor: UIColor().colorConversionHex(Color_Value: "#F5F5F5"), startPoint: CGPoint(x: 0.5, y: 0), endPoint: CGPoint(x: 0.5, y: 1))
        
        createUI()
        autoConnectToDevice()
//        checkWiFi()
    }
    
    func createUI() {
        collectionLayout = UICollectionViewFlowLayout.init()
        collectionLayout.scrollDirection = .vertical
        collectionLayout.minimumInteritemSpacing = 16
        collectionLayout.minimumLineSpacing = 0
        collectionView.collectionViewLayout = collectionLayout
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UINib.init(nibName: "DeviceListCell", bundle: nil), forCellWithReuseIdentifier: "DeviceListCell")
    }
    func startScan() {
           guard !isScanning else { return }
           
            isScanning = true
           
           do {
               // 创建 UDP 套接字
               recsocket = GCDAsyncUdpSocket(delegate: self, delegateQueue:.main)
               
               // 绑定到本地端口
               try recsocket?.bind(toPort: 0)
               
               // 加入组播组
               try recsocket?.joinMulticastGroup(SSDP_MULTICAST_IP)
               
               // 开始接收数据
               try recsocket?.beginReceiving()
               
               // 发送 SSDP M-SEARCH 请求
               sendSearchRequest()
               
               // 设置超时计时器
               searchTimer = Timer.scheduledTimer(timeInterval: SSDP_SEARCH_TIMEOUT, target: self, selector: #selector(stopScan), userInfo: nil, repeats: false)
           } catch {
               isScanning = false
           }
       }
    // 停止扫描
        @objc func stopScan() {
            guard isScanning else { return }
            
            searchTimer?.invalidate()
            searchTimer = nil
            
            recsocket?.close()
            recsocket = nil
            
            isScanning = false
         }
        
        // 发送 SSDP 搜索请求
        private func sendSearchRequest() {
            let searchMessage = """
            M-SEARCH * HTTP/1.1\r
            HOST: \(SSDP_MULTICAST_IP):\(SSDP_PORT)\r
            MAN: "ssdp:discover"\r
            MX: 3\r
            ST: ssdp:all\r
            \r\n
            """
            
            let s = "M-SEARCH * HTTP/1.1\r\n" +
            "HOST: \(SSDP_MULTICAST_IP):\(SSDP_PORT)\r\n" +
            "MAN: \"ssdp:discover\"\r\n" +
            "MX: 2\r\n" +
            "ST: upnp:rootdevice\r\n" +
            "\r\n"
            
            XPLog(message: s)
            guard let data = s.data(using:.utf8) else { return }
            
            recsocket?.send(data, toHost: SSDP_MULTICAST_IP, port: SSDP_PORT, withTimeout: -1, tag: 0)
        }
    
    
    
    func scanWifiInfos() {
        print("1.Start")
        let nsObjectFromString: NSObject = "EFNEHotspotHelperDemo" as NSString

        let options: [String: NSObject] = [
            kNEHotspotHelperOptionDisplayName as String: nsObjectFromString
        ]
        let queue = DispatchQueue(label: "EFNEHotspotHelperDemo")
        
         let isRegistered = NEHotspotHelper.register(options: options, queue: queue) { cmd in
            print("4.Finish")
            
            if cmd.commandType == .evaluate || cmd.commandType == .filterScanList {
                for network in cmd.networkList ?? [] {
                    let wifiInfo = """
                    ---------------------------
                    SSID: \(network.ssid ?? "")
                    Mac地址: \(network.bssid ?? "")
                    信号强度: \(network.signalStrength)
                    CommandType: \(cmd.commandType.rawValue)
                    ---------------------------
                    """
                    
                    
                    XPLog(message: wifiInfo)
                    
                    // 检测到指定 WiFi 并自动连接
                    if network.ssid == "测试 WiFi" {
                        network.setConfidence(.high)
                        network.setPassword("123456789")
                        let response = cmd.createResponse(.success)
                        response.setNetwork(network)
                        response.deliver()
                    }
                }
            }
        }
        XPLog(message: "3.Result: \(isRegistered ? "Yes" : "No")")
    }
    
    func autoConnectToDevice() {
        let config = NEHotspotConfiguration(ssidPrefix: "BEVERG_", passphrase: "12345678", isWEP: false)
        config.joinOnce = true // 保持长期连接
        
        NEHotspotConfigurationManager.shared.apply(config) { error in
            if let error = error {
                self.showHUDOnlyShowMessage(messge: "连接失败：\(error.localizedDescription)")
                print("连接失败：\(error.localizedDescription)")

            } else {
                self.showHUDOnlyShowMessage(messge: "已发起自动连接请求")

                print("已发起自动连接请求")
                self.startScan()

//                self.startSocketCommunication() // 连接成功后启动数据交互
            }
        }
    }
}

extension DeviceHomeViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    // MARK: - UICollectionView did select item at indexpath
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = DeviceDetailListViewController()
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: DeviceListCell = collectionView.dequeueReusableCell(withReuseIdentifier: "DeviceListCell", for: indexPath) as! DeviceListCell
        
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    
    // MARK: - UICollectionView size for item at indexpath
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: (XSQ_Width - 48)/2, height: 112)

    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
    }
    
 }


// MARK: - Extension delegate
extension DeviceHomeViewController:GCDAsyncUdpSocketDelegate {

    // MARK: - 检查WIFI
    func checkWiFi(){
        // 检查是否连接wifi
        checkNETState()
        // 置空之前缓存的wifi 信息
        mPCIpAddress = nil
        mPCIpAddressData = nil
        
        let discoveryRequest = """
                    M-SEARCH * HTTP/1.1
                    HOST: 239.255.255.250:1900
                    MAN: "ssdp:discover"
                    MX: 5
                    ST: urn:schemas-upnp-org:device:Basic:1
                    """
        
        recsocket = GCDAsyncUdpSocket.init(delegate: self, delegateQueue: .main)
        try? recsocket.bind(toPort: UInt16(0))
//        try? recsocket.enableBroadcast(true)
        try? recsocket.beginReceiving()
        let data = discoveryRequest.data(using:.utf8)!
        recsocket.send(data, toHost: "239.255.255.250", port: 1900, withTimeout: -1, tag: 0)
    }

    func checkNETState(){
        XSQNetworking.QSmanager?.startListening(onUpdatePerforming: { (status) in
            XPLog(message: status)
            
            if status == .reachable(.ethernetOrWiFi) {
                XSQ_NetWorkType = 1
            }else if status == .notReachable {
                XSQ_NetWorkType = 0
                SVProgressHUD.showInfo(withStatus: "网络连接失败")
            }else if status == .reachable(.cellular) {
                XSQ_NetWorkType = 2
            }else{
                XSQ_NetWorkType = -1//未知网络
            }
        })
    }

    // MARK: - 检查WIFI---Delegate
    func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
        XPLog(message: "连接失败")
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
        XPLog(message: "连接成功")
        showHUDOnlyShowMessage(messge: "连接成功")

    }

    func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) {
        XPLog(message: "udpSocketDidClose")
        XPLog(message: error)
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
        XPLog(message: "发送成功")
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
        XPLog(message: "发送失败")
    }

    func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
        let addressStr = GCDAsyncUdpSocket.host(fromAddress: address)
                XPLog(message: address)
        showHUDOnlyShowMessage(messge: addressStr ?? "")

        let messageStr = String.init(data: data, encoding: .utf8)
        showHUDOnlyShowMessage(messge: messageStr ?? "")

        guard messageStr != nil else {
            return
        }
        
        if !(messageStr!.contains("teacherIOS")) {
            
            mPCIpAddressData = address
            //            XPLog(message: addressStr?.hasPrefix("192"))
            let startIndex = addressStr!.range(of: "192")?.lowerBound
            guard startIndex != nil else {
                return
            }
            
            //            XPLog(message: addressStr?.suffix(from: startIndex!))
            let dd = addressStr?.suffix(from: startIndex!)
            mPCIpAddress = String(dd ?? "")
            //            XPLog(message: "这是别人的的ip" + (addressStr ?? ""))
        }else{
            //            XPLog(message: "这是自己的ip" + (addressStr ?? ""))
        }
        
    }

}
